package y2016.date0120.pm.pull生成xml;

import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

public class XmlPullService {

    public boolean createXml(List<Note> noteList) {
        File file = new File("d:\\hao.txt");
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlSerializer serializer = factory.newSerializer();
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos, "utf-8");
            serializer.setOutput(osw);
            serializer.startDocument("utf-8", true);
            serializer.startTag(null, "yueshi");
            for (Note note : noteList) {
                serializer.startTag(null, "note");
                serializer.attribute(null, "id", note.getId() + "");
                serializer.text("\n");
                serializer.startTag(null, "name");
                serializer.text(note.getName() + "");
                serializer.endTag(null, "name");

                serializer.startTag(null, "time");
                serializer.text(note.getCreateTime() + "");
                serializer.endTag(null, "time");

                serializer.startTag(null, "path");
                serializer.text(note.getPath() + "");
                serializer.endTag(null, "path");

                serializer.startTag(null, "title");
                serializer.text(note.getTitle() + "");
                serializer.endTag(null, "title");

                serializer.startTag(null, "content");
                serializer.text(note.getContent());
                serializer.endTag(null, "content");

                serializer.endTag(null, "note");

            }
            serializer.endTag(null, "yueshi");
//			serializer.flush();
            serializer.endDocument();
            osw.flush();
            osw.close();
            fos.close();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;

    }
}


